import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';

import '../../../routes/app_routes.dart';
import 'media_list_controller.dart';
import 'widgets/media_list_filter.dart';

// Updated MediaListPage
class MediaListPage extends StatelessWidget {
  const MediaListPage({super.key});

  @override
  Widget build(BuildContext context) {
    final MediaListController controller = Get.put(MediaListController());
    final ScrollController scrollController = ScrollController();

    scrollController.addListener(() {
      if (scrollController.position.userScrollDirection == ScrollDirection.reverse && scrollController.offset > 50 && controller.isFilterExpanded.value) {
        controller.hideFilter();
      } else if (scrollController.position.userScrollDirection == ScrollDirection.forward && scrollController.offset < 50 && !controller.isFilterExpanded.value) {
        controller.showFilter();
      }
    });

    return Scaffold(
      appBar: AppBar(
        title: const Text('影视列表'),
        centerTitle: true,
      ),
      body: Obx(() => Stack(
            children: [



              CustomScrollView(
                controller: scrollController,
                slivers: [
                  // Sliver for Filter/Hidden Tag
                  SliverToBoxAdapter(
                    child: AnimatedSwitcher(
                      duration: const Duration(milliseconds: 300),
                      transitionBuilder: (child, animation) => SizeTransition(
                        sizeFactor: animation,
                        child: child,
                      ),
                      child: controller.isFilterExpanded.value
                          ? Padding(
                              key: const ValueKey(1),
                              padding: const EdgeInsets.all(8.0),
                              child: MediaListFilter(filters: controller.filters),
                            )
                          : const SizedBox.shrink(),
                    ),
                  ),
                  // Sliver for Film List
                  SliverPadding(
                    padding: const EdgeInsets.all(8.0),
                    sliver: SliverGrid(
                      delegate: SliverChildBuilderDelegate(
                        (context, index) {
                          if (index == controller.films.length) {
                            if (controller.hasMore.value) {
                              if (!controller.isLoading.value) {
                                controller.loadFilms();
                              }
                              return const Center(child: CircularProgressIndicator());
                            } else {
                              return const Center(
                                child: Text(
                                  '已经到最后一页',
                                  style: TextStyle(color: Colors.grey),
                                ),
                              );
                            }
                          }
                          final film = controller.films[index];
                          return FilmCard(film: film);
                        },
                        childCount: controller.films.length + 1,
                      ),
                      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        crossAxisSpacing: 8.0,
                        mainAxisSpacing: 8.0,
                        childAspectRatio: 0.6,
                      ),
                    ),
                  ),
                ],
              ),
              // Hidden Tag
              if (controller.isHiddenTagVisible.value)
                Positioned(
                  top: 8,
                  left: 0,
                  right: 0,
                  child: GestureDetector(
                    onTap: controller.toggleFilter,
                    child: Container(
                      padding: const EdgeInsets.all(8.0),
                      color: Colors.blue.withOpacity(0.9),
                      child: const Text(
                        '已隐藏，点击显示',
                        style: TextStyle(color: Colors.white),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                ),
            ],
          )),
    );
  }
}

class FilmCard extends StatelessWidget {
  final Map<String, dynamic> film;

  const FilmCard({Key? key, required this.film}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Get.toNamed(AppRoutes.MediaDetailPage, parameters: {
          "title": "最近播放记录",
          "contentType": "history",
        });
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8.0),
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Stack(
                    children: [
                      Image.network(
                        film['imageUrl'] ?? "http://192.168.1.8:9001/p2896940977.webp",
                        width: double.infinity,
                        height: double.infinity,
                        fit: BoxFit.cover,
                        errorBuilder: (_, __, ___) => const Center(
                          child: Icon(Icons.broken_image, color: Colors.grey),
                        ),
                      ),
                      Positioned(
                        bottom: 0,
                        left: 0,
                        right: 0,
                        child: Container(
                          height: 40,
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              begin: Alignment.bottomCenter,
                              end: Alignment.topCenter,
                              colors: [
                                Colors.black.withOpacity(0.7),
                                Colors.transparent,
                              ],
                            ),
                          ),
                        ),
                      ),
                      if (film.containsKey('rating'))
                        Positioned(
                          bottom: 4,
                          right: 4,
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 4.0, vertical: 2.0),
                            decoration: BoxDecoration(
                              color: Colors.black.withOpacity(0.6),
                              borderRadius: BorderRadius.circular(4.0),
                            ),
                            child: Text(
                              film['rating'],
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 10,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 4.0, vertical: 4.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        film['title'] ?? '未知标题',
                        style: const TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 2.0),
                      Text(
                        film['releaseDate'] ?? '未知日期',
                        style: TextStyle(
                          fontSize: 10,
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
